package delegate4j;

import com.sun.istack.internal.Nullable;

import java.util.ArrayList;
import java.util.concurrent.FutureTask;

public class Func4<T1, T2, T3, T4, TResult> extends Delegate<IFunc4<T1, T2, T3, T4, TResult>> {
    public Func4() {
    }

    public Func4(IFunc4<T1, T2, T3, T4, TResult> delegate) {
        super(delegate);
    }

    public TResult invoke(T1 t1, T2 t2, T3 t3, T4 t4) throws Exception {
        TResult result = null;
        for (int i = 0; i < delegates.size(); i++) {
            result = delegates.get(i).invoke(t1, t2, t3, t4);
        }
        return result;
    }

    public AsyncResult<TResult> invokeAsync(T1 t1, T2 t2, T3 t3, T4 t4, @Nullable Callback callback) {
        ArrayList<FutureTask<TResult>> tasks = new ArrayList<>();
        for (int i = 0; i < delegates.size(); i++) {
            tasks.add(delegates.get(i).invokeAsync(t1, t2, t3, t4, null));
        }

        waitTasksFinish(tasks, new Object[]{t1, t2, t3, t4}, callback);

        //返回tasks的浅拷贝
        return new AsyncResult<>(tasks);
    }
}